package com.label.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.label.Dao.ActivityMapper;
import com.label.Dao.ConditionMapper;
import com.label.Dao.StrategyMapper;
import com.label.Model.Do.Activity;
import com.label.Model.Do.Condition;
import com.label.Model.Do.Persons;
import com.label.Model.Do.Strategy;
import com.label.Model.Query.ActivityQuery;
import com.label.Service.ActivityService;
import com.label.Utils.UserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Transactional(rollbackFor = {Exception.class})
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private StrategyMapper strategyMapper;

    @Resource
    private ConditionMapper conditionMapper;

    @Resource
    @Qualifier("sparkSqlJdbcTemplate")
    private JdbcTemplate sparkJdbc;

    @Resource
    @Qualifier("oracleJdbcTemplate")
    private JdbcTemplate oracleJdbc;

    @Override
    public Activity getOneById(ActivityQuery activityQuery){
        Activity activity=activityMapper.getOneById(activityQuery.getId());
        if(activity.getStrategyId()!=null){
            Strategy strategy=strategyMapper.getOneById(Long.valueOf(activity.getStrategyId()));
            if(strategy!=null)
                activity.setStrategy(strategy);
        }
        return activity;
    }

    @Override
    public List<Activity> getAllActivity(){
        List<Activity> activities=activityMapper.getAll();
        List<Long> strategyIds=activities.stream().filter(p->p.getStrategyId()!=null).map(p->Long.valueOf(p.getStrategyId())).distinct().collect(Collectors.toList());
        Map<String,Object> strategies=strategyIds.isEmpty()?new HashMap<>():strategyMapper.selectBatchIds(strategyIds).stream().collect(Collectors.toMap(p->p.getId().toString(), p->p));

        activities.forEach(p->{if(p.getStrategyId()!=null && strategies.containsKey(p.getStrategyId()))p.setStrategy((Strategy) strategies.get(p.getStrategyId()));});
        return activities;
    }

    @Override
    public List<Activity> getAllByLevel(ActivityQuery activityQuery){
        if(activityQuery.getLevels()!=null && !activityQuery.getLevels().isEmpty()){
            List<Activity> activities=new ArrayList<>();
            for (String level:activityQuery.getLevels()){
                activities.addAll(activityMapper.getAllByLevel(level));
            }
            List<Long> strategyIds=activities.stream().filter(p->p.getStrategyId()!=null).map(p->Long.valueOf(p.getStrategyId())).distinct().collect(Collectors.toList());
            Map<String,Object> strategies=strategyIds.isEmpty()?new HashMap<>():strategyMapper.selectBatchIds(strategyIds).stream().collect(Collectors.toMap(p->p.getId().toString(), p->p));

            activities.forEach(p->{if(p.getStrategyId()!=null && strategies.containsKey(p.getStrategyId()))p.setStrategy((Strategy) strategies.get(p.getStrategyId()));});
            return activities;
        }
        return null;
    }

    @Override
    public List<Activity> getAllByName(ActivityQuery activityQuery){
        if(activityQuery.getName()!=null && !StringUtils.isBlank(activityQuery.getName())){
            List<Activity> activities=activityMapper.getAllByName(activityQuery.getName());
            List<Long> strategyIds=activities.stream().filter(p->p.getStrategyId()!=null).map(p->Long.valueOf(p.getStrategyId())).distinct().collect(Collectors.toList());
            Map<String,Object> strategies=strategyIds.isEmpty()?new HashMap<>():strategyMapper.selectBatchIds(strategyIds).stream().collect(Collectors.toMap(p->p.getId().toString(), p->p));

            activities.forEach(p->{if(p.getStrategyId()!=null && strategies.containsKey(p.getStrategyId()))p.setStrategy((Strategy) strategies.get(p.getStrategyId()));});
            return activities;
        }
        return null;
    }


    @Override
    public List<Activity> getAllByUser(String id){
        List<Map<String,Object>> idMap=oracleJdbc.queryForList("select activity_id from activity_attend where user_id='"+id+"' group by activity_id ");
        if(!idMap.isEmpty()){
            List<String> ids= idMap.stream().map(p->p.get("ACTIVITY_ID").toString()).collect(Collectors.toList());
            List<Activity> activities=activityMapper.getAllByIds(ids);
            List<Long> strategyIds=activities.stream().filter(p->p.getStrategyId()!=null).map(p->Long.valueOf(p.getStrategyId())).distinct().collect(Collectors.toList());
            Map<String,Object> strategies=strategyIds.isEmpty()?new HashMap<>():strategyMapper.selectBatchIds(strategyIds).stream().collect(Collectors.toMap(p->p.getId().toString(), p->p));

            activities.forEach(p->{if(p.getStrategyId()!=null && strategies.containsKey(p.getStrategyId()))p.setStrategy((Strategy) strategies.get(p.getStrategyId()));});
            return activities;
        }
        return null;
    }

    @Override
    public Boolean addActivity(ActivityQuery activityQuery){
        Activity activity=BeanUtil.copyProperties(activityQuery,Activity.class,"tags");
        activityMapper.insert(activity);
        if(activityQuery.getTags()!=null && !activityQuery.getTags().isEmpty()){
            activityMapper.saveActivityTag(activity.getId(),activityQuery.getTags());
        }
        return true;
    }

    @Override
    public Boolean updateActivity(ActivityQuery activityQuery){
        if(!BeanUtil.isEmpty(activityQuery,"tags","id")){
            activityMapper.updateById(BeanUtil.copyProperties(activityQuery,Activity.class,"tags"));
        }
        if(activityQuery.getTags()!=null){
            activityMapper.delActivityTag(activityQuery.getId());
            if(!activityQuery.getTags().isEmpty())
                activityMapper.saveActivityTag(activityQuery.getId(),activityQuery.getTags());
        }
        return true;
    }

    @Override
    public Boolean delActivity(ActivityQuery activityQuery){
        activityMapper.deleteById(activityQuery.getId());
        activityMapper.delActivityTag(activityQuery.getId());
        return true;
    }

    @Override
    public List<Map<String,Object>> getActScoreByUser(){
        return oracleJdbc.queryForList("select userid,activityid,activityname,activitytime,yearandseme,rewardtype,cast(virtue as decimal(18,2)),cast(wisdom as decimal(18,2)),cast(sports as decimal(18,2)),cast(art as decimal(18,2)),cast(labour as decimal(18,2)),cast(rewardresult as decimal(18,2)) from studentactivity where userid='"+UserUtil.getUserId()+"' and activityid is NOT NULL");
//        return sparkJdbc.queryForList("select userid,activityid,activityname,activitytime,yearandseme,rewardtype,cast(virtue as decimal(18,2)),cast(wisdom as decimal(18,2)),cast(sports as decimal(18,2)),cast(art as decimal(18,2)),cast(labour as decimal(18,2)),cast(rewardresult as decimal(18,2)) from hive.studentactivity where userid='"+UserUtil.getUserId()+"' and activityid is NOT NULL");
    }

    @Override
    public List<Condition> getAllCondition() {
        return conditionMapper.selectList(new QueryWrapper<>());
    }

}
